<?php
    class SectionRepository
    {
        var $db;

        function SectionRepository(){
            global $SERVER, $DATABASE, $USERNAME, $PASSWORD;
            $this->db = new Connection($SERVER, $DATABASE, $USERNAME, $PASSWORD);
        }

        function GetAll()
        {
            if(isset($this->db))
            {
                $result = $this->db->ExecuteQuery("select * from section");
                return $this->ChangeToArray($result);
            }
        }
        
        function GetSection($id)
        {
            $result = $this->db->ExecuteQuery("select * from section where ID_i=" . $id);
            if($row = mysql_fetch_array($result)){
                return new SectionEntity($row[0], $row[1], $row[2]);
            }
            return null;
        }

        function ChangeToArray($result)
        {
            $array = array();
            $count = 0;
            while($row = mysql_fetch_array($result, MYSQL_NUM))
            {
                $entity = new SectionEntity($row[0], $row[1], $row[2]);
                $array[$count++] = $entity;
            }
            return $array;
        }

        function Insert(SectionEntity $entity)
        {
            $query = "INSERT INTO section(Name_s, Description_s) VALUES(";
            $query.="'".$entity->Name_s."',";
            $query.="'".$entity->Description_s."')";
            return $this->db->ExecuteQuery($query);
        }
        
        function Delete($id)
        {
            $query = "DELETE FROM section WHERE ID_i=" . $id;
            return $this->db->ExecuteQuery($query);
        }
    
        function Update(SectionEntity $entity)
        {
            $query = "UPDATE section SET ";
            $query .= "Name_s='" . $entity->Name_s . "',";
            $query .= "Description_s='" . $entity->Description_s . "'";
            $query .= " WHERE ID_i=" . $entity->ID_i;
            return $this->db->ExecuteQuery($query);
        }
    }
?>
